Product Code Database
Example Keywords: ipad -winter $95-128
barcode-scavenger
   » » Wiki: Dom Event
Tag Wiki 'Dom Event'.
Tag

DOM (Document Object Model) Events are a signal that something has occurred, or is occurring, and can be triggered by user interactions or by the browser. scripting languages like , , , and Java can register various event handlers or listeners on the element nodes inside a DOM tree, such as in , , , and SVG documents.

Examples of DOM Events:

  • When a user clicks the mouse
  • When a web page has loaded
  • When an image has been loaded
  • When the mouse moves over an element
  • When an input field is changed
  • When an HTML form is submitted
  • When a user presses a key

Historically, like DOM, the event models used by various had some significant differences which caused compatibility problems. To combat this, the event model was standardized by the World Wide Web Consortium (W3C) in DOM Level 2.


Events

HTML events

Common events
There is a huge collection of events that can be generated by most element nodes:
  • events.
  • Keyboard events.
  • HTML frame/object events.
  • HTML form events.
  • User interface events.
  • Mutation events (notification of any changes to the structure of a document).
  • Progress events (used by and File API).

Note that the event classification above is not exactly the same as W3C's classification.

MouseclickonclickFires when the button is clicked over an element. A click is defined as a mousedown and mouseup over the same screen location. The sequence of these events is:
  • mousedown
  • mouseup
  • click
dblclickondblclickFires when the pointing device button is over an element
mousedownonmousedownFires when the pointing device button is pressed over an element
mouseuponmouseupFires when the pointing device button is released over an element
onmouseoverFires when the pointing device is moved onto an element
mousemoveonmousemoveFires when the pointing device is moved while it is over an element
mouseoutonmouseoutFires when the pointing device is moved away from an element
dragstartondragstartFired on an element when a drag is started.
dragondragThis event is fired at the source of the drag, that is, the element where dragstart was fired, during the drag operation.
dragenterondragenterFired when the mouse is first moved over an element while a drag is occurring.
dragleaveondragleaveThis event is fired when the mouse leaves an element while a drag is occurring.
dragoverondragoverThis event is fired as the mouse is moved over an element when a drag is occurring.
dropondropThe drop event is fired on the element where the drop occurs at the end of the drag operation.
dragendondragendThe source of the drag will receive a dragend event when the drag operation is complete, whether it was successful or not.
KeyboardkeydownonkeydownFires before keypress, when a key on the keyboard is pressed.
keypressonkeypressFires after keydown, when a key on the keyboard is pressed.
keyuponkeyupFires when a key on the keyboard is released
HTML frame/objectloadonloadFires when the finishes loading all content within a document, including window, frames, objects and images For elements, it fires when the target element and all of its content has finished loading
unloadonunloadFires when the user agent removes all content from a window or frame For elements, it fires when the target element or any of its content has been removed
abortonabortFires when an object/image is stopped from loading before completely loaded
erroronerrorFires when an object/image/frame cannot be loaded properly
resizeonresizeFires when a document view is resized
scrollonscrollFires when an element or document view is scrolled, except that a scroll event on document must bubble to the window
HTML formselectonselectFires when a user selects some text in a , including input and textarea
changeonchangeFires when a control loses the input focus and its value has been modified since gaining focus
submitonsubmitFires when a form is submitted
resetonresetFires when a form is reset
focusonfocusFires when an element receives focus either via the pointing device or by
bluronblurFires when an element loses focus either via the pointing device or by tabbing navigation
User interfacefocusin Similar to HTML focus event, but can be applied to any focusable element
focusout Similar to HTML blur event, but can be applied to any focusable element
DOMActivate Similar to XUL command event. Fires when an element is activated, for instance, through a mouse click or a keypress.
MutationDOMSubtreeModified Fires when the subtree is modified
DOMNodeInserted Fires when a node has been added as a child of another node
DOMNodeRemoved Fires when a node has been removed from a DOM-tree
DOMNodeRemovedFromDocument Fires when a node is being removed from a document
DOMNodeInsertedIntoDocument Fires when a node is being inserted into a document
DOMAttrModified Fires when an attribute has been modified
DOMCharacterDataModified Fires when the character data has been modified
Progressloadstart Progress has begun.
progress In progress. After loadstart has been dispatched.
error Progression failed. After the last progress has been dispatched, or after loadstart has been dispatched if progress has not been dispatched.
abort Progression is terminated. After the last progress has been dispatched, or after loadstart has been dispatched if progress has not been dispatched.
load Progression is successful. After the last progress has been dispatched, or after loadstart has been dispatched if progress has not been dispatched.
loadend Progress has stopped. After one of error, abort, or load has been dispatched.

Note that the events whose names start with "DOM" are currently not well supported, and for this and other performance reasons are deprecated by the W3C in DOM Level 3. and Opera support DOMAttrModified, DOMNodeInserted, DOMNodeRemoved and DOMCharacterDataModified. and Safari support these events, except for DOMAttrModified.


Touch events
Web browsers running on devices, such as Apple's iOS and Google's Android, generate additional events.
Touchtouchstart Fires when a finger is placed on the touch surface/screen.
touchend Fires when a finger is removed from the touch surface/screen.
touchmove Fires when a finger already placed on the screen is moved across the screen.
touchenter Fires when a touch point moves onto the interactive area defined by a DOM element.
touchleave Fires when a touch point moves off the interactive area defined by a DOM element.
touchcancel A must dispatch this event type to indicate when a TouchPoint has been disrupted in an implementation-specific manner, such as by moving outside the bounds of the UA window. A user agent may also dispatch this event type when the user places more touch points (The coordinate point at which a pointer (e.g. finger or stylus) intersects the target surface of an interface) on the touch surface than the device or implementation is configured to store, in which case the earliest TouchPoint object in the TouchList should be removed.

In the W3C draft recommendation, a TouchEvent delivers a TouchList of Touch locations, the that were active, a TouchList of Touch locations within the targeted DOM element, and a TouchList of Touch locations that have changed since the previous TouchEvent.

Apple didn't join this working group, and delayed W3C recommendation of its Touch Events Specification by disclosing late in the recommendation process.


Pointer events
Web browsers on devices with various types of input devices including mouse, touch panel, and pen may generate integrated input events. Users can see what type of input device is pressed, what button is pressed on that device, and how strongly the button is pressed when it comes to a stylus pen. As of October 2013, this event is only supported by Internet Explorer 10 and 11.
PointerpointerdownonpointerdownFires when the pointing device button is activated, or pressed over an element.
pointeruponpointerupFires when the pointing device button is released over an element
pointercancelonpointercancelFires when a pointing device is unlikely to continue to produce event because, for example, the device is used for panning/zooming after a pointerdown event.
pointermoveonpointermoveFires when the pointing device is moved while it is over an element
pointeroveronpointeroverFires when the pointing device is moved onto an element
pointeroutonpointeroutFires when the pointing device is moved away from an element. Also fires after pointerup by pointing device without hovering, or after
pointerenteronpointerenterFires when the pointing device is moved onto an element, or when the button of the pointing device which does not support hovering is pressed on one of its descendant elements.
pointerleaveonpointerleaveFires when the pointing device is moved away from an element, or when the button of the pointing device which does not support hovering is released over its descendant elements.
gotpointercaptureongotpointercaptureFires when the pointer is captured by setPointerCapture method.
lostpointercaptureonlostpointercaptureFires when the pointer is released by releasePointerCapture method.


Indie UI events
Not yet really implemented, the Indie UI working groups want to help web application developers to be able to support standard user interaction events without having to handle different platform specific technical events that could match with it.

Scripting usable interfaces can be difficult, especially when one considers that user interface design patterns differ across software platforms, hardware, and locales, and that those interactions can be further customized based on personal preference. Individuals are accustomed to the way the interface works on their own system, and their preferred interface frequently differs from that of the web application author's preferred interface.

For example, web application authors, wishing to intercept a user's intent to undo the last action, need to "listen" for all the following events:

  • Control+Z on Windows and Linux.
  • Command+Z on Mac OS X.
  • Shake events on some mobile devices.

It would be simpler to listen for a single, normalized request to "undo" the previous action.

RequestundorequestIndicates the user desires to "undo" the previous action. (May be superseded by the UndoManager interface.)
redorequestIndicates the user desires to "redo" the previously "undone" action. (May be superseded by the UndoManager interface.)
expandrequestIndicates the user desires to reveal information in a collapsed section (e.g. a disclosure widget) or branch node in a hierarchy (e.g., a ).
collapserequestIndicates the user desires to hide or collapse information in an expanded section (e.g. a disclosure widget) or branch node in a hierarchy (e.g., a tree view).
dismissrequestIndicates the user desires "dismiss" the current view (e.g. canceling a dialog, or closing a popup menu).
deleterequestIndicates the user wants to initiate a "delete" action on the marked element or current view.
Focus RequestdirectionalfocusrequestInitiated when the user agent sends a "direction focus" request to the web application. Web authors should not use or register for directionalfocusrequest events when standard browser focus and blur events are sufficient. Using these events unnecessarily could result in reduced performance or negative user experience.
linearfocusrequestInitiated when the user agent sends a "linear focus" request to the web application. Web authors should not use or register for linearfocusrequest events when standard browser focus and blur events are sufficient. This event type is only necessary on specialized control types such as data grids where the logical next element may not be focusable or even in the DOM until requested. Using these events unnecessarily could result in reduced performance or negative user experience.
palettefocusrequestInitiated when the user agent sends a "palette focus" request to the web application. Web app authors receiving this event should move focus to the first palette in the web application, or cycle focus between all available palettes. Note: palettes are sometimes referred to as non-modal dialogs or inspector windows.
toolbarfocusrequestInitiated when the user agent sends a "toolbar focus" request to the web application. Web app authors receiving this event should move focus to the main toolbar in the web application, or cycle focus between all available toolbars.
Manipulation RequestmoverequestInitiated when the user agent sends a move request to the web application with accompanying x/y delta values. This is used, for example, when moving an object to a new location on a layout canvas.
panrequestInitiated when the user agent sends a pan request to the web application with accompanying x/y delta values. This is used, for example, when changing the center point while panning a map or another custom image viewer.
rotationrequestInitiated when the user agent sends a rotation request to the web application with accompanying origin x/y values and a rotation value in degrees.
zoomrequestInitiated when the user agent sends a zoom request to the web application with accompanying origin x/y values and the zoom scale factor.
Scroll RequestscrollrequestInitiated when the user agent sends a scroll request to the web application with accompanying x/y delta values or one of the other defined scrollType values. Authors should only use this event and uiaction with custom scroll views.
ValueChange RequestvaluechangerequestInitiated when the user agent sends a value change request to the web application. Used on custom range controls like sliders, carousels, etc.


Internet Explorer-specific events
In addition to the common (W3C) events, two major types of events are added by Internet Explorer. Some of the events have been implemented as de facto standards by other browsers.
  • Clipboard events.
  • Data binding events.

ClipboardcutoncutFires after a selection is cut to the clipboard.
copyoncopyFires after a selection is copied to the clipboard.
pasteonpasteFires after a selection is pasted from the clipboard.
beforecutonbeforecutFires before a selection is cut to the clipboard.
beforecopyonbeforecopyFires before a selection is copied to the clipboard.
beforepasteonbeforepasteFires before a selection is pasted from the clipboard.
Data bindingafterupdateonafterupdateFires immediately after a databound object has been updated.
beforeupdateonbeforeupdateFires before a data source is updated.
cellchangeoncellchangeFires when a data source has changed.
dataavailableondataavailableFires when new data from a data source become available.
datasetchangedondatasetchangedFires when content at a data source has changed.
datasetcompleteondatasetcompleteFires when transfer of data from the data source has completed.
errorupdateonerrorupdateFires if an error occurs while updating a data field.
rowenteronrowenterFires when a new row of data from the data source is available.
rowexitonrowexitFires when a row of data from the data source has just finished.
rowsdeleteonrowsdeleteFires when a row of data from the data source is deleted.
rowinsertedonrowinsertedFires when a row of data from the data source is inserted.
MousecontextmenuoncontextmenuFires when the context menu is shown.
dragondragFires when during a mouse drag (on the moving Element).
dragstartondragstartFires when a mouse drag begins (on the moving Element).
dragenterondragenterFires when something is dragged onto an area (on the target Element).
dragoverondragoverFires when a drag is held over an area (on the target Element).
dragleaveondragleaveFires when something is dragged out of an area (on the target Element).
dragendondragendFires when a mouse drag ends (on the moving Element).
dropondropFires when a mouse button is released over a valid target during a drag (on the target Element).
selectstartonselectstartFires when the user starts to select text.
KeyboardhelponhelpFires when the user initiates help.
HTML frame/objectbeforeunloadonbeforeunloadFires before a document is unloaded.
stoponstopFires when the user stops loading the object. (unlike abort, stop event can be attached to document)
HTML formbeforeeditfocusonbeforeeditfocusFires before an element gains focus for editing.
MarqueestartonstartFires when a marquee begins a new loop.
finishonfinishFires when marquee looping is complete.
bounceonbounceFires when a scrolling marquee bounces back in the other direction.
MiscellaneousbeforeprintonbeforeprintFires before a document is printed
afterprintonafterprintFires immediately after the document prints.
propertychangeonpropertychangeFires when the property of an object is changed.
filterchangeonfilterchangeFires when a filter changes properties or finishes a transition.
readystatechangeonreadystatechangeFires when the readyState property of an element changes.
losecaptureonlosecaptureFires when the releaseCapture method is invoked.

Note that Mozilla, Safari and Opera also support the readystatechange event for the object. Mozilla also supports the beforeunload event using the traditional event registration method (DOM Level 0). Mozilla and Safari also support contextmenu, but Internet Explorer for Mac does not.

Note that Firefox 6 and later support the beforeprint and afterprint events.


XUL events
In addition to the common (W3C) events, Mozilla defined a set of events that work only with elements.

MouseDOMMouseScrollDOMMouseScrollFires when the mouse wheel is moved, causing the content to scroll.
dragdropondragdropFires when the user releases the mouse button to drop an object being dragged.
dragenterondragenterFires when the mouse pointer first moves over an element during a drag. It is similar to the mouseover event but occurs while dragging.
dragexitondragexitFires when the mouse pointer moves away from an element during a drag. It is also called after a drop on an element. It is similar to the mouseout event but occurs during a drag.
draggestureondraggestureFires when the user starts dragging the element, usually by holding down the mouse button and moving the mouse.
dragoverondragoverRelated to the mousemove event, this event is fired while something is being dragged over an element.
InputCheckboxStateChange Fires when a checkbox is checked or unchecked, either by the user or a script.
RadioStateChange Fires when a radio button is selected, either by the user or a script.
closeoncloseFires when a request has been made to close the window.
commandoncommandSimilar to W3C DOMActivate event. Fires when an element is activated, for instance, through a mouse click or a keypress.
inputoninputFires when a user enters text in a textbox.
User interfaceDOMMenuItemActiveDOMMenuItemActiveFires when a menu or menuitem is , or highlighted.
DOMMenuItemInactiveDOMMenuItemInactiveFires when a menu or menuitem is no longer being hovered over, or highlighted.
contextmenuoncontextmenuFires when the user requests to open the context menu for the element. The action to do this varies by platform, but it will typically be a right click.
overflowonoverflowFires a box or other layout element when there is not enough space to display it at full size.
overflowchangedonoverflowchangedFires when the overflow state changes.
underflowonunderflowFires to an element when there becomes enough space to display it at full size.
popuphiddenonpopuphiddenFires to a popup after it has been hidden.
popuphidingonpopuphidingFires to a popup when it is about to be hidden.
popupshowingonpopupshowingFires to a popup just before it is popped open.
popupshownonpopupshownFires to a popup after it has been opened, much like the onload event is sent to a window when it is opened.
CommandbroadcastonbroadcastPlaced on an observer. The broadcast event is sent when the attributes of the broadcaster being listened to are changed.
commandupdateoncommandupdateFires when a command update occurs.


Other events
For Mozilla and Opera 9, there are also undocumented events known as DOMContentLoaded and DOMFrameContentLoaded which fire when the DOM content is loaded. These are different from "load" as they fire before the loading of related files (e.g., images). However, DOMContentLoaded has been added to the HTML 5 specification. The DOMContentLoaded event was also implemented in the rendering engine build 500+.[1] This correlates to all versions of and Safari 3.1+. DOMContentLoaded is also implemented in Internet Explorer 9.

Opera 9 also supports the Web Forms 2.0 events DOMControlValueChanged, invalid, forminput and formchange.


Event flow
Consider the situation when two event targets participate in a tree. Both have event listeners registered on the same event type, say "click". When the user clicks on the inner element, there are two possible ways to handle it:
  • Trigger the elements from outer to inner (event capturing). This model is implemented in Netscape Navigator.
  • Trigger the elements from inner to outer (). This model is implemented in Internet Explorer and other browsers.

W3C takes a middle position in this struggle.

According to the W3C, events go through three phases when an event target participates in a tree:

  1. The capture phase: the event travels down from the root event target to the target of an event
  2. The target phase: the event travels through the event target
  3. The bubble phase ( optional): the event travels back up from the target of an event to the root event target. The bubble phase will only occur for events that bubble (where event.bubbles == true)

You can find a visualization of this event flow at https://domevents.dev


Stopping events
While an event is travelling through event listeners, the event can be stopped with event.stopPropagation() or event.stopImmediatePropagation()

  • event.stopPropagation(): the event is stopped after all event listeners attached to the current event target in the current event phase are finished
  • event.stopImmediatePropagation(): the event is stopped immediately and no further event listeners are executed

When an event is stopped it will no longer travel along the event path. Stopping an event does not cancel an event.


Legacy mechanisms to stop an event
  • Set the event.cancelBubble to true (Internet Explorer)
  • Set the event.returnValue property to false


Canceling events
A cancelable event can be canceled by calling event.preventDefault(). Canceling an event will opt out of the default browser behaviour for that event. When an event is canceled, the event.defaultPrevented property will be set to true. Canceling an event will not stop the event from traveling along the event path.


Event object
The Event object provides a lot of information about a particular event, including information about target element, key pressed, mouse button pressed, mouse position, etc. Unfortunately, there are very serious browser incompatibilities in this area. Hence only the W3C Event object is discussed in this article.

+Event properties ! Name ! Type ! Description
typeDOMStringThe name of the event (case-insensitive in DOM level 2 but case-sensitive in DOM level 3 ).
targetEventTargetUsed to indicate the EventTarget to which the event was originally dispatched.
currentTargetEventTargetUsed to indicate the EventTarget whose EventListeners are currently being processed.
eventPhaseunsigned shortUsed to indicate which phase of event flow is currently being evaluated.
bubblesbooleanUsed to indicate whether or not an event is a bubbling event.
cancelablebooleanUsed to indicate whether or not an event can have its default action prevented.
timeStampDOMTimeStampUsed to specify the time (in milliseconds relative to the epoch) at which the event was created.

+Event methods ! Name ! Argument type ! Argument name ! Description
stopPropagation To prevent further propagation of an event during event flow.
preventDefault To cancel the event if it is cancelable, meaning that any default action normally taken by the implementation as a result of the event will not occur.
initEventDOMStringeventTypeArgSpecifies the event type.
booleancanBubbleArgSpecifies whether or not the event can bubble.
booleancancelableArgSpecifies whether or not the event's default action can be prevented.


Event handling models

DOM Level 0
This event handling model was introduced by Netscape Navigator, and remains the most cross-browser model . There are two model types: the inline model and the traditional model.


Inline model
In the inline model, event handlers are added as attributes of elements. In the example below, an alert dialog box with the message "Hey Joe" appears after the is clicked. The default click action is cancelled by returning false in the event handler.


     Inline Event Handling
     

Inline Event Handling

Hey Joe!


     

One common misconception with the inline model is the belief that it allows the registration of event handlers with custom arguments, e.g. name in the triggerAlert function. While it may seem like that is the case in the example above, what is really happening is that the JavaScript engine of the browser creates an anonymous function containing the statements in the onclick attribute. The onclick handler of the element would be bound to the following anonymous function:

function () {

triggerAlert('Joe');
return false;
     
}

This limitation of the JavaScript event model is usually overcome by assigning attributes to the function object of the event handler or by using closures.


Traditional model
In the traditional model, event handlers can be added or removed by scripts. Like the inline model, each event can only have one event handler registered. The event is added by assigning the handler name to the event property of the element object. To remove an event handler, simply set the property to null:

     Traditional Event Handling
     

Traditional Event Handling

Hey Joe!


     

To add parameters: var name = 'Joe'; document.onclick = (function (name) {

return function () {
	alert('Hey ' + name + '!');
};
     
}(name));

Inner functions preserve their scope.


DOM Level 2
The W3C designed a more flexible event handling model in DOM Level 2.

addEventListenerAllows the registration of event listeners on the event target.DOMStringtype
EventListenerlistener
booleanuseCapture
removeEventListenerAllows the removal of event listeners from the event target.DOMStringtype
EventListenerlistener
booleanuseCapture
dispatchEventAllows sending the event to the subscribed event listeners.Eventevt

Some useful things to know :

  • To prevent an event from bubbling, developers must call the stopPropagation() method of the event object.
  • To prevent the default action of the event to be called, developers must call the preventDefault() method of the event object.

The main difference from the traditional model is that multiple event handlers can be registered for the same event. The useCapture option can also be used to specify that the handler should be called in the capture phase instead of the bubbling phase. This model is supported by , , Safari, and .


A rewrite of the example used in the traditional model
    
    DOM Level 2
     

    

DOM Level 2

    

Hey Joe!

    
     


Internet Explorer-specific model
Microsoft Internet Explorer prior to version 8 does not follow the W3C model, as its own model was created prior to the ratification of the W3C standard. Internet Explorer 9 follows DOM level 3 events, and Internet Explorer 11 deletes its support for Microsoft-specific model.

attachEventSimilar to W3C's addEventListener method.StringsEvent
PointerfpNotify
detachEventSimilar to W3C's removeEventListener method.StringsEvent
PointerfpNotify
fireEventSimilar to W3C's dispatchEvent method.StringsEvent
EventoEventObject

Some useful things to know :

  • To prevent an event bubbling, developers must set the event's cancelBubble property.
  • To prevent the default action of the event to be called, developers must set the event's returnValue property.
  • The this keyword refers to the global window object.

Again, this model differs from the traditional model in that multiple event handlers can be registered for the same event. However the useCapture option can not be used to specify that the handler should be called in the capture phase. This model is supported by Microsoft Internet Explorer and Trident based browsers (e.g. , Avant Browser).


A rewrite of the example used in the old Internet Explorer-specific model
    
    Internet Explorer-specific model
     
    

Internet Explorer-specific model

    

Hey Joe!

    
     


Further reading
  • Deitel, Harvey. (2002). Internet and World Wide Web: how to program (Second Edition).
  • The Mozilla Organization. (2009). DOM Event Reference. Retrieved August 25, 2009.
  • Quirksmode (2008). Event compatibility tables. Retrieved November 27, 2008.
  • http://www.sitepen.com/blog/2008/07/10/touching-and-gesturing-on-the-iphone/


External links

Page 1 of 1
1
Page 1 of 1
1

Account

Social:
Pages:  ..   .. 
Items:  .. 

Navigation

General: Atom Feed Atom Feed  .. 
Help:  ..   .. 
Category:  ..   .. 
Media:  ..   .. 
Posts:  ..   ..   .. 

Statistics

Page:  .. 
Summary:  .. 
1 Tags
10/10 Page Rank
5 Page Refs
1s Time